package com.cml.getway.core.netty.processor.filter.error;

import com.cml.getway.common.config.Rule;
import com.cml.getway.common.constants.ProcessorFilterConstants;
import com.cml.getway.common.enums.ResponseCode;
import com.cml.getway.common.exception.GetwayBaseException;
import com.cml.getway.core.context.Context;
import com.cml.getway.core.context.GetwayResponse;
import com.cml.getway.core.netty.processor.filter.AbstractEntryProcessorFilter;
import com.cml.getway.core.netty.processor.filter.Filter;
import com.cml.getway.core.netty.processor.filter.ProcessorFilterType;

/**
 * 姓名：陈茂林
 * 时间：2024/1/29
 * 描述：
 */
@Filter(
        id = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ID,
        name = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_NAME,
        value = ProcessorFilterType.ERROR,
        order = ProcessorFilterConstants.DEFAULT_ERROR_FILTER_ORDER
)
public class DefaultErrorFilter extends AbstractEntryProcessorFilter<Rule.FilterConfig> {

    public DefaultErrorFilter() {
        super(Rule.FilterConfig.class);
    }

    @Override
    public void entry(Context ctx, Object... args) throws Throwable {
        try {
            Throwable throwable = ctx.getThrowable();
            ResponseCode responseCode = ResponseCode.INTERNAL_ERROR;
            if(throwable instanceof GetwayBaseException) {
                GetwayBaseException getwayBaseException = (GetwayBaseException)throwable;
                responseCode = getwayBaseException.getCode();
            }
            GetwayResponse getwayResponse = GetwayResponse.buildRapidResponse(responseCode);
            ctx.setResponse(getwayResponse);
        } finally {
            System.err.println("============> do error filter <===============");
            //	设置写回标记
            ctx.writtened();
            //	触发后面的过滤器执行
            super.fireNext(ctx, args);
        }
    }

}